//
//  LXHttpRequestManager.m
//  bgms_p
//
//  Created by xiao.zhao@lachesis-mh.com on 16/2/19.
//  Copyright © 2016年 xiao.zhao@lachesis-mh.com. All rights reserved.
//

#import "LXHttpRequestManager.h"
#import "LXLoginVC.h"

@interface LXHttpRequestManager ()

@end

@implementation LXHttpRequestManager

static LXHttpRequestManager *_sessionManager = nil;
static dispatch_once_t onceToken;

+ (LXHttpRequestManager *)manager
{
    dispatch_once(&onceToken, ^{
        _sessionManager = [[LXHttpRequestManager alloc] init];
    });
    
    return _sessionManager;
}

- (NetworkStatus)checkNetworkState
{
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
    NetworkStatus status = [conn currentReachabilityStatus];
    switch (status) {
        case NotReachable:
            
            break;
            
        case ReachableViaWiFi:
            
            break;
            
        case ReachableViaWWAN:
            
            break;
            
        default:
            break;
    }
    return status;
}

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
        [securityPolicy setAllowInvalidCertificates:YES];
        NSString *ipString = [self getObjectForKey:@"baseURL"];
        if (!ipString) {
            ipString = @"";
        }
        NSURL *url = [NSURL URLWithString:ipString];
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _sessionManager = [[LXHttpRequestManager alloc] initWithBaseURL:url sessionConfiguration:config];
        
        AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
        requestSerializer.timeoutInterval = 30.0f;
        _sessionManager.requestSerializer = requestSerializer;
        
        AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
        responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/plain", nil];
        _sessionManager.responseSerializer = responseSerializer;
        
        [_sessionManager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch (status) {
                case AFNetworkReachabilityStatusNotReachable:
                {
                    [_sessionManager.operationQueue setSuspended:YES];
                }
                    break;
                case AFNetworkReachabilityStatusReachableViaWiFi:
                {
                    [_sessionManager.operationQueue setSuspended:NO];
                }
                    break;
                case AFNetworkReachabilityStatusReachableViaWWAN:
                {
                    [_sessionManager.operationQueue setSuspended:NO];
                }
                    break;
                    
                default:
                    break;
            }
        }];
        [_sessionManager.reachabilityManager startMonitoring];
    }
    
    return _sessionManager;
}

-(void)sendSyncPostRequest:(NSString *)requestUrl parameters:(NSDictionary *)params success:(void (^)(id, NSString *))success failure:(void (^)(NSString *))failure
{
    NSMutableURLRequest *request = [_sessionManager.requestSerializer requestWithMethod:@"POST" URLString:requestUrl parameters:params error:nil];
    
    AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    requestOperation.responseSerializer = _sessionManager.responseSerializer;
    
    [_sessionManager.operationQueue addOperations:@[requestOperation] waitUntilFinished:YES];
    
    if(requestOperation.error)
    {
        if(failure)
        {
            failure(requestOperation.error.localizedDescription);
        }
    }
    else
    {
        if(success)
        {
            NSData *responseData = requestOperation.responseObject;
            NSDictionary *responseDic = [responseData objectFromJSONData];
            
            NSString *msg = [responseDic objectForKey:@"msg"];
            NSInteger responseCode = [[responseDic objectForKey:@"code"] integerValue];
            id response = [responseDic objectForKey:@"data"];

            if(responseCode == 0) {
                success(response, msg);
            } else if (responseCode == 11120105) {
                LXLoginVC *loginVC = [[LXLoginVC alloc] init];
                LXThemeColorNavigationController *themeNav = [[LXThemeColorNavigationController alloc] initWithRootViewController:loginVC];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:themeNav animated:YES completion:nil];
                });
            } else {
                failure(msg);
            }
        }
    }
}

-(void)GET:(NSString *)URLString parameters:(id)parameters token:token success:(void (^)(id, NSString *))success failure:(void (^)(NSString *))failure
{
    if ([self checkNetworkState] != NotReachable) {
        if(token)
        {
            [_sessionManager.requestSerializer setValue:token forHTTPHeaderField:@"Token"];
        }
        [_sessionManager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"Bgmsclient"];
        
        [_sessionManager GET:URLString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
            
            NSData *responseData = responseObject;
            NSDictionary *responseDic = [responseData objectFromJSONData];
            
            NSString *msg = [responseDic objectForKey:@"msg"];
            NSInteger responseCode = [[responseDic objectForKey:@"code"] integerValue];
            id response = [responseDic objectForKey:@"data"];
            
            if (responseCode == 0) {
                success(response, msg);
            } else if (responseCode == 11120105) {
                LXLoginVC *loginVC = [[LXLoginVC alloc] init];
                LXThemeColorNavigationController *themeNav = [[LXThemeColorNavigationController alloc] initWithRootViewController:loginVC];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:themeNav animated:YES completion:nil];
                });
            } else {
                failure(msg);
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            failure(error.localizedDescription);
        }];
    } else {
        failure(@"网络异常，请检查您的网络");
    }
}

-(void)POST:(NSString *)URLString parameters:(id)parameters token:token success:(void (^)(id, NSString *))success failure:(void (^)(NSString *))failure
{
    if ([self checkNetworkState] != NotReachable) {
        if(token)
        {
            [_sessionManager.requestSerializer setValue:token forHTTPHeaderField:@"Token"];
        }
        [_sessionManager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"Bgmsclient"];
        [_sessionManager POST:URLString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject){
            
            NSData *responseData = responseObject;
            NSDictionary *responseDic = [responseData objectFromJSONData];
            
            NSString *msg = [responseDic objectForKey:@"msg"];
            NSInteger responseCode = [[responseDic objectForKey:@"code"] integerValue];
            id response = [responseDic objectForKey:@"data"];
            
            if(responseCode == 0) {
                success(response, msg);
            } else if (responseCode == 11120105) {
                LXLoginVC *loginVC = [[LXLoginVC alloc] init];
                LXThemeColorNavigationController *themeNav = [[LXThemeColorNavigationController alloc] initWithRootViewController:loginVC];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:themeNav animated:YES completion:nil];
                });
            } else {
                failure(msg);
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            failure(error.localizedDescription);
        }];
    } else {
        failure(@"网络异常，请检查您的网络");
    }
}

- (void)PUT:(NSString *)URLString parameters:(id)parameters token:token success:(void (^)(id response, NSString *msg))success failure:(void (^)(NSString *msg))failure
{
    if ([self checkNetworkState] != NotReachable) {
        if(token)
        {
            [_sessionManager.requestSerializer setValue:token forHTTPHeaderField:@"Token"];
        }
        [_sessionManager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"Bgmsclient"];
        
        [_sessionManager PUT:URLString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
            
            NSData *responseData = responseObject;
            NSDictionary *responseDic = [responseData objectFromJSONData];
            
            NSString *msg = [responseDic objectForKey:@"msg"];
            NSInteger responseCode = [[responseDic objectForKey:@"code"] integerValue];
            id response = [responseDic objectForKey:@"data"];
            
            if(responseCode == 0) {
                success(response, msg);
            } else if (responseCode == 11120105) {
                LXLoginVC *loginVC = [[LXLoginVC alloc] init];
                LXThemeColorNavigationController *themeNav = [[LXThemeColorNavigationController alloc] initWithRootViewController:loginVC];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:themeNav animated:YES completion:nil];
                });
            } else {
                failure(msg);
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            failure(error.localizedDescription);
        }];
    } else {
        failure(@"网络异常，请检查您的网络");
    }
}

- (void)DELETE:(NSString *)URLString parameters:(id)parameters token:token success:(void (^)(id response, NSString *msg))success failure:(void (^)(NSString *msg))failure
{
    if ([self checkNetworkState] != NotReachable) {
        if(token)
        {
            [_sessionManager.requestSerializer setValue:token forHTTPHeaderField:@"Token"];
        }
        [_sessionManager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"Bgmsclient"];
        
        [_sessionManager DELETE:URLString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
            
            NSData *responseData = responseObject;
            NSDictionary *responseDic = [responseData objectFromJSONData];
            
            NSString *msg = [responseDic objectForKey:@"msg"];
            NSInteger responseCode = [[responseDic objectForKey:@"code"] integerValue];
            id response = [responseDic objectForKey:@"data"];
            
            if(responseCode == 0) {
                success(response, msg);
            } else if (responseCode == 11120105) {
                LXLoginVC *loginVC = [[LXLoginVC alloc] init];
                LXThemeColorNavigationController *themeNav = [[LXThemeColorNavigationController alloc] initWithRootViewController:loginVC];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:themeNav animated:YES completion:nil];
                });
            } else {
                failure(msg);
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            failure(error.localizedDescription);
        }];
    } else {
        failure(@"网络异常，请检查您的网络");
    }
}

-(void)uploadTaskWithUrl:(NSString *)urlString parameters:(id)parameters token:token success:(void (^)(id, NSString *))success failure:(void (^)(NSString *))failure
{
    if ([self checkNetworkState] != NotReachable) {
        [_sessionManager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"Bgmsclient"];
        if(token)
        {
            [_sessionManager.requestSerializer setValue:token forHTTPHeaderField:@"Token"];
        }
        NSData *bodyData = parameters[@"bodyData"];
        NSString *dataName = parameters[@"dataName"];//ios多传一个name参数，对应接口处的data实体名
        NSString *imageName = parameters[@"imageName"];
        [_sessionManager POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileData:bodyData name:dataName fileName:imageName mimeType:@"image/jpeg"];
        } success:^(NSURLSessionDataTask *task, id responseObject) {
            
            NSData *responseData = responseObject;
            NSDictionary *responseDic = [responseData objectFromJSONData];
            
            NSString *msg = [responseDic objectForKey:@"msg"];
            NSInteger responseCode = [[responseDic objectForKey:@"code"] integerValue];
            id response = [responseDic objectForKey:@"data"];
            
            if(responseCode == 0) {
                success(response, msg);
            } else if (responseCode == 11120105) {
                LXLoginVC *loginVC = [[LXLoginVC alloc] init];
                LXThemeColorNavigationController *themeNav = [[LXThemeColorNavigationController alloc] initWithRootViewController:loginVC];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:themeNav animated:YES completion:nil];
                });
            } else {
                failure(msg);
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            failure(error.localizedDescription);
        }];
    } else {
        failure(@"网络异常，请检查您的网络");
    }
}

//-(void)downloadTaskWithRequest:(NSURLRequest *)request progress:(NSProgress *__autoreleasing *)progress destination:(NSURL *(^)(NSURL *, NSURLResponse *))destination completionHandler:(void (^)(NSURLResponse *, NSURL *, NSError *))completionHandler
//{
//    NSURLSessionDownloadTask *task = [_sessionManager downloadTaskWithRequest:request progress:progress destination:destination completionHandler:completionHandler];
//    
//    [task resume];
//}

-(void)cancelAll
{
    NSArray *tasks = [_sessionManager dataTasks];
    for (NSURLSessionTask *task in tasks) {
        [task cancel];
    }
}

- (void)resetManagerBaseURLWithSt1:(NSString *)st1 nd2:(NSString *)nd2 rd3:(NSString *)rd3 th4:(NSString *)th4 port:(NSString *)port
{
    NSString *URLString = [NSString stringWithFormat:@"http://%@.%@.%@.%@:%@/", st1, nd2, rd3, th4, port];
    [self saveObject:URLString forKey:@"baseURL"];
    
    _sessionManager = nil;
    onceToken = 0;
}

- (void)resetServiceAddress:(NSString *)URLString
{
    URLString = [URLString stringByReplacingOccurrencesOfString:@"http://" withString:@""];
    NSRange range = [URLString rangeOfString:@"."];
    self.st1    = [URLString substringToIndex:range.location];
    URLString   = [URLString substringFromIndex:range.location + 1];
    range       = [URLString rangeOfString:@"."];
    self.nd2    = [URLString substringToIndex:range.location];
    URLString   = [URLString substringFromIndex:range.location + 1];
    range       = [URLString rangeOfString:@"."];
    self.rd3    = [URLString substringToIndex:range.location];
    URLString   = [URLString substringFromIndex:range.location + 1];
    range       = [URLString rangeOfString:@":"];
    self.th4    = [URLString substringToIndex:range.location];
    URLString   = [URLString substringFromIndex:range.location + 1];
    self.port   = [URLString stringByReplacingOccurrencesOfString:@"/" withString:@""];
}
@end
